package netty.chat.server.binary;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import netty.chat.protocal.ProtocalMsg;
import netty.chat.service.MsgService;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * �����ҵ������
 */
public class BinaryServerHandler extends SimpleChannelInboundHandler {

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    public static Map<String,Channel> userChannels = new ConcurrentHashMap<String, Channel>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channels.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channels.remove(ctx.channel());
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
        ProtocalMsg msgObj = (ProtocalMsg) msg;
        Channel incoming = ctx.channel();

        //����ģʽ
        doSingleChat(msgObj, incoming);
    }

    private void doSingleChat(ProtocalMsg msgObj, Channel incoming) {
        //System.out.println("doSingleChat");
        //����ҵ����
        MsgService.getInstance().handle(msgObj,incoming);
    }

    private void doGroupChat(ProtocalMsg msgObj, Channel incoming) {
        for (Channel channel : channels) {
            if (channel != incoming) {
                //System.out.println("send to channel " + channel.remoteAddress() + " with msg:" + msgObj.getContent());
                System.out.println(msgObj.getContent());
                channel.writeAndFlush(msgObj);
            }
        }
    }

}
